//
//  TodayView.m
//  Bracelet
//
//  Created by jing zhao on 2/12/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//

#import "Mycity_TodayView.h"

#import "APImycityTodayTotal.h"
#import "Mycity_RankCell.h"
#import "Mycity_RankHeaderView.h"
#import "APIMycityGetTotalRankData.h"

#define  MOVEDIFFERENT      45.0f
@interface Mycity_TodayView()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_topViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_bottomViewToTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_containerViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_PercentViewTopSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_YouLabelToTOP;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_buttonToTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint_BottomViewToBottom;

@property (weak, nonatomic) IBOutlet UIView *       ui_viewContainer;
@property (weak, nonatomic) IBOutlet UIView *       ui_top;
@property (weak, nonatomic) IBOutlet UILabel *      ui_labelNextChange;
@property (weak, nonatomic) IBOutlet UITableView *  ui_tableViewRank;
@property (weak, nonatomic) IBOutlet UILabel *      ui_labelTotalWalkers;
@property (weak, nonatomic) IBOutlet UILabel *      ui_labelTextYou;
@property (weak, nonatomic) IBOutlet UILabel *      ui_labelRank;
@property (weak, nonatomic) IBOutlet UIView *       ui_viewBottom;
@property (weak, nonatomic) IBOutlet UIButton *     ui_buttonPutUpAndDown;
@property (weak, nonatomic) IBOutlet UIWebView *    ui_webView;
@property (weak, nonatomic) IBOutlet UIView *       ui_tapMovePosition;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *ui_activityView;

@property(strong, nonatomic)APIOneCityTotalRank* myRank;
@property (strong, nonatomic)NSMutableArray *arrayAllRank;
@property (strong, nonatomic)APIPaper *paper;
@property (copy, nonatomic) NSString*totalRunners;
@property (unsafe_unretained, nonatomic)BOOL boolRefresh;


@property (unsafe_unretained, nonatomic) BOOL   boolMoveBoomView;
@property (unsafe_unretained, nonatomic) BOOL   boolTouch;
@property (unsafe_unretained, nonatomic) BOOL   boolUp;
@end


@implementation Mycity_TodayView


-(void)initWithType:(NSString*)type
{
    if ([type isEqualToString:@"HBCN"])
        return;
    self.boolRefresh = NO;
    self.boolMoveBoomView = NO;
    self.boolTouch = NO;
    self.ui_tableViewRank.delegate = self;
    self.ui_tableViewRank.dataSource = self;
    
    [self.ui_activityView startAnimating];
//    [self updateNetwork];
    self.ui_webView.scrollView.scrollEnabled = NO;
    self.ui_webView.delegate = self;
}

-(void)layoutSubviews
{
    self.constraint_topViewHeight.constant = self.frame.size.height-MOVEDIFFERENT;
    self.constraint_containerViewHeight.constant = self.frame.size.height*2-MOVEDIFFERENT;
    [super layoutSubviews];
}

#pragma network
-(void)updateNetwork
{
  UIRefreshTableView *refresh = (UIRefreshTableView*)self.superview;
  [APImycityTodayTotal getMyCityTodayDataSuccess:^(APImycityTodayTotal *mycity) {
    
    [self.ui_webView loadHTMLString:mycity.strHtml baseURL:nil];
    //self.ui_labelTotalWalkers.text = mycity.strCityTotleWalkers;
      [self setTotalWalkersLabel:mycity.strCityTotleWalkers];
    self.ui_labelNextChange.text = mycity.strCityNextChanllengeTarget;
//    self.ui_labelRank.text = [NSString stringWithFormat:@"NO.%@",mycity.strCityRunRanking];
//    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Your city ranks %@ among all cities",self.ui_labelRank.text]];
//    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Univers Next for HSBC W01 Rg" size:14.0] range:NSMakeRange(16, [self.ui_labelRank.text length])];
//    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(16, [self.ui_labelRank.text length])];
//    self.ui_labelTextYou.attributedText = str;
    if ([self.ui_activityView isAnimating]) {
      [self.ui_activityView stopAnimating];
    }
    [refresh endRefreshData];
  } failure:^(NSError *error) {
    [refresh endRefreshData];
    if ([self.ui_activityView isAnimating]) {
      [self.ui_activityView stopAnimating];
    }
  }];
  [APIMycityGetTotalRankData getCityRankOfCityWithPagePaper:@"1" getTheTotalRank:^(APIMycityGetTotalRankData *totoalRank) {
    self.arrayAllRank = totoalRank.arrayAllRank;
    self.myRank = totoalRank.myRank;
    self.paper = totoalRank.paper;
    [self.ui_tableViewRank reloadData];
      [self setlabelRank:_myRank.strCityRunRanking];
    [self createFootViewWithPaper];
    [refresh endRefreshData];
  } failure:^(NSError *error) {
    [refresh endRefreshData];
    //errror
  }];
}


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  
  NSString *urlstr = request.URL.absoluteString;
  NSRange range = [urlstr rangeOfString:@"ios://"];
  if (range.length!=0) {
    NSString *method = [urlstr substringFromIndex:(range.location+range.length)];
    SEL selctor = NSSelectorFromString(method);
    SuppressPerformSelectorLeakWarning([self performSelector:selctor withObject:nil]);
  }
  return YES;
}
-(void)loadingPage{
  NSLog(@"loadingpage !!!");
  
  [[NSNotificationCenter defaultCenter]postNotificationName:@"CharityWalkathon" object:nil];
  
}

- (void)scrollDownWithAimation:(float)time
{
    self.constraint_bottomViewToTop.constant = 0;
    self.constraint_BottomViewToBottom.constant = 0;
    [self.ui_viewBottom setNeedsUpdateConstraints];
    
    self.constraint_YouLabelToTOP.constant = 0;
    [self.ui_labelTextYou setNeedsUpdateConstraints];
    
    self.constraint_buttonToTop.constant = 28.0f;
    [self.ui_buttonPutUpAndDown setNeedsUpdateConstraints];
    
    self.constraint_PercentViewTopSpace.constant =0.0;
    [self.ui_labelRank setNeedsUpdateConstraints];
    
    [UIView animateWithDuration:time animations:^{
        [self.ui_viewBottom layoutIfNeeded];
        [self.ui_labelTextYou layoutIfNeeded];
        [self.ui_labelRank layoutIfNeeded];
        [self.ui_buttonPutUpAndDown layoutIfNeeded];
        [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageDown"] forState:UIControlStateNormal];
    } completion:^(BOOL finished) {
        self.boolMoveBoomView = NO;
        if([self.superview isKindOfClass:[UITableView class]])
        {
            UITableView *tableView = (UITableView*)self.superview;
            tableView.scrollEnabled = YES;
        }
    }];
}

- (void)scrollUpWithAnimation:(float)time
{
    self.constraint_bottomViewToTop.constant = -self.frame.size.height+MOVEDIFFERENT;
    self.constraint_BottomViewToBottom.constant = self.frame.size.height - MOVEDIFFERENT;
    [self.ui_viewBottom setNeedsUpdateConstraints];
    
    self.constraint_YouLabelToTOP.constant = 39.0;
    [self.ui_labelTextYou setNeedsUpdateConstraints];
    
    self.constraint_buttonToTop.constant = 0.0f;
    [self.ui_buttonPutUpAndDown setNeedsUpdateConstraints];
    
    self.constraint_PercentViewTopSpace.constant =39.0;
    [self.ui_labelRank setNeedsUpdateConstraints];
    
    [UIView animateWithDuration:time animations:^{
        [self.ui_viewBottom layoutIfNeeded];
        [self.ui_labelTextYou layoutIfNeeded];
        [self.ui_labelRank layoutIfNeeded];
        [self.ui_buttonPutUpAndDown layoutIfNeeded];
        [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageUp"] forState:UIControlStateNormal];
    } completion:^(BOOL finished) {
        self.boolMoveBoomView = NO;
        if([self.superview isKindOfClass:[UITableView class]])
        {
            UITableView *tableView = (UITableView*)self.superview;
            tableView.scrollEnabled = NO;
        }
    }];
}

//bottom  tableView

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.arrayAllRank) {
        if ([self.arrayAllRank count]==0)
            self.ui_tableViewRank.hidden = YES;
        else
            self.ui_tableViewRank.hidden = NO;
        
        return [self.arrayAllRank count];
    }
    
    self.ui_tableViewRank.hidden = YES;
    return 0;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    Mycity_RankHeaderView *headerview = [[[NSBundle mainBundle]loadNibNamed:@"Mycity_RankHeaderView" owner:self options:nil]lastObject];
    headerview.frame = CGRectMake(0, 0, self.ui_tableViewRank.frame.size.width, 100);
    [headerview setMyRank:self.myRank andTotalrunners:self.totalRunners];
    return headerview;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"strTableViewCell";
    Mycity_RankCell *cell = (Mycity_RankCell*)[tableView dequeueReusableCellWithIdentifier:str];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"Mycity_RankCell" owner:self options:nil]lastObject];
    }
    APIOneCityTotalRank *oneRank = [self.arrayAllRank objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;    
    [cell setApiOneRank:oneRank];
    return cell;
}

/********************************************下拉刷新***/
-(void)createFootViewWithPaper
{
  //    if (self.paper.totalPages == self.paper.pageNo) {
  //        self.ui_tableViewRank.tableFooterView = nil;
  //         self.boolRefresh = YES;
  //    }
  //    else if (self.paper.totalPages > self.paper.pageNo)
  //    {
  self.boolRefresh = NO;
  UIView *tableViewFooter = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.ui_tableViewRank.bounds.size.width, 50.0)];
  UILabel *loadMoreText = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f,self.ui_tableViewRank.bounds.size.width, 50.0f)];
  [loadMoreText setCenter:tableViewFooter.center];
  [loadMoreText setTextColor:[UIColor colorWithRed:110.0/255.0 green:110.0/255.0 blue:110.0/255.0 alpha:1.0]];
  [loadMoreText  setFont:[UIFont systemFontOfSize:12.0f]];
  if (self.paper.totalPages == self.paper.pageNo){
    [loadMoreText setText:@"No more data"];
    self.boolRefresh = YES;
  }else{
    [loadMoreText setText:@"Pull up to show more results"];
  }
  [loadMoreText setTextAlignment:NSTextAlignmentCenter];
  
  UIActivityIndicatorView *tableFooterActivityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(75.0f, 10.0f, 20.0f, 20.0f)];
  [tableFooterActivityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
  [tableFooterActivityIndicator stopAnimating];
  tableFooterActivityIndicator.center = tableViewFooter.center;
  [tableViewFooter addSubview:tableFooterActivityIndicator];
  [tableViewFooter addSubview:loadMoreText];
  self.ui_tableViewRank.tableFooterView = tableViewFooter;
  //    }
  
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // 下拉到最底部时显示更多数据
    if(!self.boolRefresh&&scrollView.contentOffset.y > ((scrollView.contentSize.height - scrollView.frame.size.height)))
    {
        self.boolRefresh = YES;
        [self loadDataBegin];
    }
}

-(void)loadDataBegin
{
    for (UIView* view in self.ui_tableViewRank.tableFooterView.subviews) {
        if ([view  isMemberOfClass:[UIActivityIndicatorView class]]) {
            [(UIActivityIndicatorView*)view startAnimating];
        }
    }
     [APIMycityGetTotalRankData getCityRankOfCityWithPagePaper:[NSString stringWithFormat:@"%i",self.paper.pageNo+1]
                                               getTheTotalRank:^(APIMycityGetTotalRankData *outRank)
                            {
                                self.paper = outRank.paper;
                                [self.arrayAllRank addObjectsFromArray:outRank.arrayAllRank];
                                [self.ui_tableViewRank reloadData];
                                
                                [self createFootViewWithPaper];
                                
                            } failure:^(NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:@"network error" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
                                [alert show];
                            }];
}
/*touch 事件为了控制分屏滚动*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.boolMoveBoomView)
        return;
    CGPoint point = [[touches  anyObject]locationInView:self.ui_viewBottom];
    
   if (CGRectContainsPoint(self.ui_tapMovePosition.frame, point))  {
        
       UIScrollView *scrollView =(UIScrollView*)self.superview.superview;
       scrollView.scrollEnabled = NO;
       UIRefreshTableView *refresh = (UIRefreshTableView*)self.superview;
       refresh.scrollEnabled = NO;
       
        self.boolMoveBoomView = YES;
        self.boolTouch        = YES;
        self.boolUp           = NO;
        
        if (self.constraint_bottomViewToTop.constant >-10)
            self.boolUp = YES;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self. boolTouch == YES) {
        UITouch *touch = [[touches allObjects]lastObject];
        
        CGPoint pointCurrent = [touch locationInView:self];
        CGPoint pointPrevious = [touch previousLocationInView:self];
        
        float differntY = pointCurrent.y -pointPrevious.y;
        if ([self changeTheTopAndBoomMove:self.constraint_bottomViewToTop.constant+differntY withBoolUp:self.boolUp]) {
            self.constraint_bottomViewToTop.constant +=differntY;
            self.constraint_BottomViewToBottom.constant -=differntY;
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self. boolTouch == YES)
        [self endMove];
    
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self. boolTouch == YES)
        [self endMove];
}

-(void)endMove
{
    UIScrollView *scrollView =(UIScrollView*)self.superview.superview;
    if (self.boolUp) {
        [self scrollUpWithAnimation:0.1];
        scrollView.scrollEnabled = NO;
    }
    else{
        [self scrollDownWithAimation:0.1];
        scrollView.scrollEnabled = YES;
    }

    UIRefreshTableView *refresh = (UIRefreshTableView*)self.superview;
    refresh.scrollEnabled = YES;
    
    self.boolMoveBoomView= YES;
    self.boolTouch = NO;
    
}

//这个float
-(BOOL)changeTheTopAndBoomMove:(float)floatMoveTo
                    withBoolUp:(BOOL)up
{
    if (floatMoveTo>0 || floatMoveTo <-self.frame.size.height+MOVEDIFFERENT) {
        return NO;
    }
    if (up) {
        if (floatMoveTo < -self.frame.size.height+MOVEDIFFERENT && self.constraint_YouLabelToTOP.constant !=39.0) {
            self.constraint_buttonToTop.constant = 0.0f;
            self.constraint_YouLabelToTOP.constant = 39.0;
            self.constraint_PercentViewTopSpace.constant =39.0;
            [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageUp"] forState:UIControlStateNormal];
        }
        else if(floatMoveTo >-self.frame.size.height+MOVEDIFFERENT && self.constraint_YouLabelToTOP.constant !=0)
        {
            self.constraint_buttonToTop.constant = 39.0f;
            self.constraint_YouLabelToTOP.constant =0.0;
            self.constraint_PercentViewTopSpace.constant = 0;
            [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageDown"] forState:UIControlStateNormal];
        }
    }
    else
    {
        if (floatMoveTo <-5 && self.constraint_YouLabelToTOP.constant !=39.0) {
            self.constraint_buttonToTop.constant = 0.0f;
            self.constraint_YouLabelToTOP.constant = 39.0;
            self.constraint_PercentViewTopSpace.constant =39.0;
            [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageUp"] forState:UIControlStateNormal];
        }
        else if(floatMoveTo >-5 && self.constraint_YouLabelToTOP.constant !=0)
        {
            self.constraint_buttonToTop.constant = 39.0f;
            self.constraint_YouLabelToTOP.constant = 0;
            self.constraint_PercentViewTopSpace.constant =0.0;
            [self.ui_buttonPutUpAndDown setImage:[UIImage imageNamed:@"icon_Button-PageDown"] forState:UIControlStateNormal];
        }
    }
    return YES;
}
- (void)setTotalWalkersLabel:(NSString *)totalStr{
    NSMutableAttributedString *totalWalkersStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ walkers",totalStr]];
    [totalWalkersStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Univers Next for HSBC W01 Lt" size:28.0] range:NSMakeRange(0, [totalStr length]+1)];
    [totalWalkersStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [totalWalkersStr length])];
    
    [totalWalkersStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Univers Next for HSBC W01 Lt" size:16.0] range:NSMakeRange([totalStr length]+1,[totalWalkersStr length]-[totalStr length]-1 )];
    self.ui_labelTotalWalkers.attributedText = totalWalkersStr;
}

- (void)setlabelRank:(NSString *)str_{
    NSString *numStr = [NSString stringWithFormat:@"NO.%@",str_];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Your city ranks %@ among all cities",numStr]];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Univers Next for HSBC W01 Rg" size:14.0] range:NSMakeRange(16, [numStr length])];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(16, [numStr length])];
    self.ui_labelTextYou.attributedText = str;
}

@end
